import React, { useEffect, useState, useRef } from 'react';
import { Modal, Input, Button, message } from 'antd';
import { CloseCircleOutlined } from '@ant-design/icons';
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';
import { toJS } from '@formily/reactive';
import { TextWidget, getMessage } from '@inbiz/react';
import ModelContent from './ModalContent';
// import nowStyle from './index.less';
import { InbizIcon } from '@inbiz/utils';
import './index.less';

/*
   categoryType:
   0.焦点图片
   1.新闻咨询

   pos(默认值为[]):
   默认展开的层级key

   id(默认为'')：
   默认选中的key
*/
export type choeseData = [{
  id: string;
  categoryType: number;
  title: string;
  pos: React.Key[];
}];

type IProps = {
  categoryType: 0 | 1;
  value: choeseData;
  onChange?: (value: any) => any;
  defaultValue: any;
};

const ClassPicker = (props: IProps) => {
  const modelContentRef = useRef(null as any);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]); // 展开父级使用pos
  const [selectId, setSelectId] = useState<any>();//选中值
  const [selectGroup, $selectGroup] = useState<any>();
  const fixValue = Array.isArray(props.value) ? props.value : props.value ? [props.value] : [];

  // 右侧属性值，默认给空字符串
  const { onChange } = props;
  const [nowValue, setNowValue] = useState([]);

  useEffect(() => {
    fixValue ? setNowValue(toJS(fixValue || []) as typeof nowValue) : setNowValue([]);
  }, [props.value]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  // 对话框
  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setExpandedKeys([]);
  };
  const handleOk = async () => {
    let result = await modelContentRef.current?.getData();
    onChange?.(result);
    // selected.id && selected.id?.length > 0 && onChange(selected)
    // setAutoExpandParent(true)
    setIsModalVisible(false);
  };

  // 删除
  const del = (id: string) => {
    const nowGroup = nowValue.filter((item: any) => item.id != id);
    setNowValue(nowGroup);
    $selectGroup(nowGroup);
    onChange?.(nowGroup);
  };
  const move = (array: any[], fromIndex: number, toIndex: number) => {
    const newArray = [...array];
    const startIndex = fromIndex < 0 ? newArray.length + fromIndex : fromIndex;
    if (startIndex >= 0 && startIndex < newArray.length) {
      const endIndex = toIndex < 0 ? newArray.length + toIndex : toIndex;
      const [item] = newArray.splice(fromIndex, 1);
      newArray.splice(endIndex, 0, item);
    }
    return newArray;
  }
  // 拖动排序
  const onSortEnd = async ({
    oldIndex,
    newIndex,
  }: {
    oldIndex: number;
    newIndex: number;
  }) => {
    try {
      if (oldIndex !== newIndex) {
        const arr = move(nowValue, oldIndex, newIndex);
        setNowValue(arr);
        onChange?.(arr);
      }
    } catch (err) {
      message.error(
        <TextWidget>ClassPicker.message_sort_fial</TextWidget>,
      );
    }
  };
  return (
    <>
      <div className="choseInput">
        <Button type="primary" onClick={showModal}>选择</Button>
        {nowValue?.length > 0 && (
          <SortableList
            nowValue={nowValue}
            onSortEnd={onSortEnd}
            del={del}
            useDragHandle
          />
        )}
        {/* <Input
          className="ipt"
          maxLength={0}
          allowClear
          value={nowValue.title}
          placeholder={getMessage('ClassPicker.pleaseSelect')} // 请选择
          readOnly
          suffix={
            nowValue.title && nowValue.title?.length > 0 ? (
              <CloseCircleOutlined
                onClick={() => {
                  const changeData = {
                    ...nowValue,
                    id: '',
                    title: '',
                    pos: [],
                  };
                  onChange ? onChange(changeData) : '';
                }}
              />
            ) : (
              ''
            )
          }
        /> */}
      </div>

      <Modal
        className="modelContainer"
        width={'30%'}
        title={
          <div className="titleText">
            <TextWidget>ClassPicker.classfySelect</TextWidget>
          </div>
        } // 分类选择
        centered
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={getMessage('global.sure')} // 确认
        cancelText={getMessage('global.cancel')} // 取消
        destroyOnClose
      >
        <ModelContent
          {...props}
          ref={modelContentRef}
          value={nowValue}
          expandedKeys={expandedKeys}
          setExpandedKeys={setExpandedKeys}
          selectId={selectId}
          setSelectId={setSelectId}
          onChange={(value) => {
            setNowValue(value);
            onChange?.(value);
          }}
        />
      </Modal>
    </>
  );
};

export default ClassPicker;

const DragHandle = SortableHandle(() => (
  <>
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="12"
      height="12"
      viewBox="0 0 12 12"
    >
      <g id="拖动排序" transform="translate(-5273 -5499)">
        <g id="组_5531" data-name="组 5531" transform="translate(4593 5321)">
          <circle
            id="椭圆_178"
            data-name="椭圆 178"
            cx="1"
            cy="1"
            r="1"
            transform="translate(682 178)"
            fill="#ccc"
          />
          <circle
            id="椭圆_179"
            data-name="椭圆 179"
            cx="1"
            cy="1"
            r="1"
            transform="translate(688 178)"
            fill="#ccc"
          />
          <circle
            id="椭圆_180"
            data-name="椭圆 180"
            cx="1"
            cy="1"
            r="1"
            transform="translate(682 183)"
            fill="#ccc"
          />
          <circle
            id="椭圆_181"
            data-name="椭圆 181"
            cx="1"
            cy="1"
            r="1"
            transform="translate(688 183)"
            fill="#ccc"
          />
          <circle
            id="椭圆_182"
            data-name="椭圆 182"
            cx="1"
            cy="1"
            r="1"
            transform="translate(682 188)"
            fill="#ccc"
          />
          <circle
            id="椭圆_183"
            data-name="椭圆 183"
            cx="1"
            cy="1"
            r="1"
            transform="translate(688 188)"
            fill="#ccc"
          />
        </g>
      </g>
    </svg>
  </>
));

const SortableItem = SortableElement(
  ({ item, del }: { item: any; del: (id: string) => void }) => (
    <div className='message-list-sort-item'>
      <p>{item?.title}</p>
      <div>
        <InbizIcon type="icon-ic-delete" onClick={() => del(item.id)} />
        <DragHandle />
      </div>
    </div>
  ),
);

const SortableList = SortableContainer(
  ({ nowValue, del }: { nowValue: any[]; del: (id: string) => void }) => {
    return (

      <div className='list' style={{ display: Array.isArray(nowValue[0]) ? 'none' : 'block' }}>
        {
          nowValue.map((item: any, idx: number) => {
            return (
              <SortableItem item={item} key={item?.id} index={idx} del={del} />
            );
          })}
      </div>
    );
  },
);
